<script setup lang="ts">
import { delRoleUserAPI, getRoleDetailAPI, getRoleListAPI, getRoleUserAPI, getTreeListAPI } from '@/apis/system';
import type { Role, RoleData, RoleUser } from '@/types/system';
import { onMounted, ref } from 'vue';
import userImage from "@/assets/user.svg";
import userActiveImage from "@/assets/user-active.svg";
import { ElMessage, ElMessageBox, type TreeInstance } from 'element-plus';
import { useRouter } from 'vue-router';

const roleList = ref<Role[]>([])
const activeIndex = ref(0)

const changeActiveIndex = (index: number) => {
  activeIndex.value = index

  // 获取当前角色下的权限点数据列表
  // 注意角色 id，不是索引
  const roleId = roleList.value[index].roleId
  console.log(roleId)
  // 如果有 roleId 就查询权限信息
  if (roleId) {
    getRoleDetail(roleId);
    getRoleUser(roleId);
  }
}
//获取角色列表
const getRoleList = async () => {
  const res = await getRoleListAPI()
  roleList.value = res.data
  const defalutRoleId = roleList.value[0].roleId;
  if (defalutRoleId) {
    getRoleDetail(defalutRoleId);
    getRoleUser(defalutRoleId);
  }
}
//对树形结构添加disabled属性
const addDisabled = (childen: RoleData[]) => {
  childen.forEach((item) => {
    item.disabled = true
    if (item.children) {
      addDisabled(item.children)
    }
  })

}
const treeList = ref<RoleData[]>([])
//获取树形结构
const getTreeList = async () => {
  const res = await getTreeListAPI()
  treeList.value = res.data
  await addDisabled(treeList.value)
}
//根据当前 roleId 获取权限点列表，并实现选中 [[11,22],[33,44]] 二维数组类型为 number[][]
const perms = ref<number[][]>([]);
// 获取 tree 组件实例，用于实现选中，注意这里写到 v-for 中，所以获取到的是数组
const treeRef = ref<TreeInstance[]>();
//获取权限列表
const getRoleDetail = async (roleId: number) => {
  const res = await getRoleDetailAPI(roleId)
  perms.value = res.data.perms
  //遍历所有树形组件实例
  treeRef.value?.forEach((treeInstance, index) => {
    //设置树形组件的选中状态
    treeInstance.setCheckedKeys(perms.value[index])
  })
}
// 6. 切换 tabs
const activeName = ref<"tree" | "member">("tree");
// 7. 获取当前角色下的成员
const roleUserList = ref<RoleUser[]>([]);
const roleUserTotal = ref(0);
const getRoleUser = async (roleId: number) => {
  const res = await getRoleUserAPI(roleId);
  roleUserList.value = res.data.rows;
  roleUserTotal.value = res.data.total;
};
const router = useRouter();
const onEditRole = (roleId: number) => {
  // 编辑和添加复用同一个表单页，编辑时把角色 id 传过去
  router.push("/roleAdd?roleId=" + roleId);
}
// 9. 删除角色
const onDeleteRole = async (roleId: number) => {
  //
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await delRoleUserAPI(roleId);
    // 删除成功，本地删除 或 重新发送请求
    roleList.value = roleList.value.filter((v) => v.roleId !== roleId);
    // 轻提示
    ElMessage.success("删除成功");
  })

};
onMounted(async () => {
  await getRoleList()
  await getTreeList()
})


</script>

<template>
  <div class="role-container">
    <div class="left-wrapper">
      <div class="role-item" @click="changeActiveIndex(index)" v-for="(item, index) in roleList" :key="item.roleId"
        :class="{ active: activeIndex === index }">
        <div class="role-info">
          <img :src="activeIndex === index ? userActiveImage : userImage" class="icon" />
        </div>
        <el-tooltip class="box-item" effect="dark" :content="item.remark" placement="top">
          <span class="name">{{ item.roleName }}</span>
        </el-tooltip>
        <div class="more">
          <el-dropdown>
            <span class="el-dropdown-link">
              <img src="@/assets/more.svg" class="icon" />
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="onEditRole(item.roleId as number)">编辑</el-dropdown-item>
                <el-dropdown-item @click="onDeleteRole(item.roleId as number)">
                  <el-text type="danger">删除</el-text>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <el-button class="addBtn" size="small" @click="$router.push('/roleAdd')">添加角色</el-button>
    </div>
    <el-tabs v-model="activeName" name="tree">
      <el-tab-pane label="功能权限">
        <div class="right-wrapper">
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree ref="treeRef" node-key="id" :data="item.children" :props="{ label: 'title' }" show-checkbox
                default-expand-all></el-tree>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="`成员(${roleUserTotal})`">
        <div class="user-wrapper">
          <el-table :data="roleUserList">
            <el-table-column label="序号" type="index" width="250" />
            <el-table-column label="员工姓名" prop="name" />
            <el-table-column label="登录帐号" prop="userName" />
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<style scoped lang="scss">
.role-container {
  display: flex;
  font-size: 14px;
  background-color: #fff;

  .left-wrapper {
    width: 200px;
    border-right: 1px solid #e4e7ec;
    padding: 4px;
    text-align: center;

    .role-item {
      position: relative;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      cursor: pointer;

      &.active {
        background: #edf5ff;
        color: #4770ff;
      }
    }

    .role-info {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 10px;
        width: 20px;
      }
    }

    .more {
      display: flex;
      align-items: center;

      .icon {
        width: 15px;
      }
    }

    .addBtn {
      width: 100%;
      margin-top: 20px;
    }
  }

  .right-wrapper {
    flex: 1;

    .tree-wrapper {
      display: flex;
      justify-content: space-between;

      .tree-item {
        flex: 1;
        border-right: 1px solid #e4e7ec;
        padding: 0px 4px;
        text-align: center;

        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }

    ::v-deep .el-tabs__nav-wrap {
      padding-left: 20px;
    }

    .user-wrapper {
      padding: 20px;
    }
  }
}
</style>